import { useMainStore } from '@/store';
import axios from 'axios';
import router from '@/router';
import Message from '@/utils/message';
import pinia from '@/store/install'; // 这个实例需要和App挂载的是同一个

axios.defaults.baseURL = '/api';
axios.defaults.timeout = 10 * 1000;

// const globalLoading = false;
// const ajaxNum = 0;
const mainStore = useMainStore(pinia);

// http request 拦截器
axios.interceptors.request.use(
  (req) => {
    req.headers = {
      'Content-Type': 'application/json;charset=UTF-8',
      Authorization: 'Bearer ' + mainStore.token,
    };
    // console.log('🚀 ~ file: http.ts ~ line 21 ~ req.headers', req.headers);

    return req;
  },
  (err) => {
    return err;
  },
);

// http response 拦截器
axios.interceptors.response.use(
  (res) => {
    console.log('res.code :: ', res);

    const data = res.data;
    if (data.code === 200) return data.data;
    Message.error(data.message);
  },
  (err) => {
    const res = err.response;

    if (res && res.status === 401) {
      Message.error('您还未登录或登录状态失效！');
      return router.push({ path: '/login' });
    } else if (res && res.status === 404) {
      Message.error('接口不存在或已被转移！');
    } else {
      Message.error('服务器异常，获取数据失败！');
    }
    Message.error(err.data.code);
    return false;
  },
);

export interface ResType<T> {
  code: number;
  data?: T;
  message: string;
  err?: string;
}

export class Http {
  static get<T>(url: string, params?: any): Promise<T> {
    return axios.get(url, params);
  }
  static put<T>(url: string, params?: any): Promise<T> {
    return axios.put(url, params);
  }
  static post<T>(url: string, params?: any): Promise<T> {
    return axios.post(url, params);
  }
  static delete<T>(url: string, params?: any): Promise<T> {
    return axios.delete(url, params);
  }
  static download(url: string) {
    const iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    iframe.src = url;
    iframe.onload = function () {
      document.body.removeChild(iframe);
    };
    document.body.appendChild(iframe);
  }
}
